package com.hengpeng.itfints.controller.borrowInfo;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.en.BorrowStatus;
import com.hengpeng.itfinbase.en.InputStatus;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.RepaymentPlan;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfints.constants.SystemConfigUtil;
import com.hengpeng.itfints.constants.TSConstants;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.controller.borrowInfo.vo.BorrowInfoVo;
import com.hengpeng.itfints.tools.PageUtil;
import com.hengpeng.itfints.vo.MemberSession;

/**
 * <pre>
 * 产品控制器
 * </pre>
 * 
 * @author weiyuan
 * @version 1.0, 2015年6月2日
 */
@Controller
@RequestMapping("/borrowInfo")
public class BorrowInfoController extends BaseController {
    /**
     * <pre>
     * 显示产品列表
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(ModelMap map, HttpServletRequest request, String curPage, String zt, String qx, String sy,
            String gm, String area, String guran) {
        int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);

        BorrowStatus[] status = { BorrowStatus.RAISE, BorrowStatus.END, BorrowStatus.LOANING,
                BorrowStatus.REPAYMENTING, BorrowStatus.REPAYMENTED };
        ServiceResult<List<BorrowInfo>> serviceResult = serviceFactory.getBorrowInfoService().queryList(status, null,
                int_curPage, 10, zt, qx, sy, gm, area, guran);
        PageUtil pUtil = new PageUtil(10, serviceResult.getReturnListSize(), int_curPage);
        map.put("dataList", serviceResult.getReturnValue());
        map.put("PageUtil", pUtil);

        map.put("zt", zt);
        map.put("qx", qx);
        map.put("sy", sy);
        map.put("gm", gm);
        map.put("area", area);
        map.put("guran", guran);
        return "/page/borrowInfo/list.jsp";
    }

    /**
     * <pre>
     * 查看产品详细信息
     * </pre>
     * 
     * @param map
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail")
    public String detail(ModelMap map, HttpServletRequest request, String borrowInfoId) {
    	MemberSession session = getSessionMember(request);
    	if (session==null) {
			return "/page/login/login.jsp";
		}
        BorrowInfo borrowInfo = serviceFactory.getBorrowInfoService().getBorrowInfo(Long.parseLong(borrowInfoId), null);
        List<InvestInfo> resultInvestInfos = serviceFactory.getInvestInfoService().queryInvestList(
                Long.parseLong(borrowInfoId), null, null);
        List<RepaymentPlan> resultRepaymentPlans = serviceFactory.getRepaymentService().getRepaymentPlans(null,
                Long.parseLong(borrowInfoId), null, null);
        map.put("borrowInfo", borrowInfo);
        map.put("investList", resultInvestInfos);
        map.put("repaymentList", resultRepaymentPlans);
        return "/page/borrowInfo/detail.jsp";
    }

    /**
     * <pre>
     * 我的融资记录列表
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/myBorrowInfoList")
    public String myBorrowInfoList(ModelMap map, HttpServletRequest request, String page, BorrowStatus borrowInfoStatus) {
        int myBorrowInfoNum = 0;
        Long myBorrowInfoMoney = 0l;
        UserInfo m = getSessionMember(request).getUser();
        List<BorrowInfoVo> dataList = serviceFactory.getBorrowInfoService().queryMyList(borrowInfoStatus, m.getId());
        int currentPage = (!StringHelper.isEmpty(page) && page != null ? Integer.parseInt(page) : 1);
        PageUtil pUtil = new PageUtil(10, dataList.size(), currentPage);

        ServiceResult<List<BorrowInfo>> serviceResult = serviceFactory.getBorrowInfoService().queryList(
                new BorrowStatus[] { BorrowStatus.RAISE, BorrowStatus.REPAYMENTING, BorrowStatus.REPAYMENTED,
                        BorrowStatus.END }, m.getId(), -1, -1, null, null, null, null, null, null);
        List<BorrowInfo> myborrowInfos = serviceResult.getReturnValue();
        if (myborrowInfos != null && myborrowInfos.size() > 0) {
            myBorrowInfoNum = myborrowInfos.size();
            for (BorrowInfo b : myborrowInfos) {
                myBorrowInfoMoney += b.getBorrowMoney() / 100;
            }
        }
        map.put("myBorrowInfoNum", myBorrowInfoNum);
        map.put("myBorrowInfoMoney", myBorrowInfoMoney);
        map.put("myBorrowInfoList", dataList);
        map.put("borrowInfoStatus", borrowInfoStatus);
        map.put("PageUtil", pUtil);
        return "/page/account/borrowinfo/index.jsp";
    }

    /**
     * <pre>
     * 转向借款
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/toBorrow")
    public String toBorrow(ModelMap map, HttpServletRequest request) {
        MemberSession member = (MemberSession) request.getSession().getAttribute(TSConstants.CLIENT_SESSION_MEMBER);
        if (member == null) {
            return "/page/borrowInfo/needLogin.jsp";// 转到登录页面
        }
        UserInfo user = member.getUser();
        map.put("user", user);
        if (user.getIsEmailCheck() == BoolValue.NO) {// 没有激活需激活
            return "/page/borrowInfo/needActive.jsp";
        }
        if (user.getType() == UserInfo.UserInfoType.PERSON) {
            return "/page/borrowInfo/cannotborrow.jsp";
        }
        return "/page/borrowInfo/addborrow.jsp";
    }

    /**
     * <pre>
     * 保存借款标的
     * </pre>
     * 
     * @param map
     * @param request
     * @param borrowInfo
     * @return
     */
    @RequestMapping(value = "/saveBorrow")
    public String saveBorrow(ModelMap map, HttpServletRequest request, BorrowInfo borrowInfo) {
        try {
            UserInfo userInfo = serviceFactory.getPersistService().get(UserInfo.class, borrowInfo.getBorrowUserId());

            // UserInfo guar =
            // GuarantorManager.getGuarantor(borrow.getGuaranteeUserId());
            borrowInfo.setBorrowUserId(userInfo.getId());
            borrowInfo.setBorrowUserName(userInfo.getUserName());
            borrowInfo.setIsMakeReceivePlan(BoolValue.NO);
            borrowInfo.setIsMakeRepayPlan(BoolValue.NO);
            borrowInfo.setBorrowUserTrustAccountId(userInfo.getTrustAccountId());
            // borrowInfo.setGuaranteeRealName(guar.getRealName());
            // borrowInfo.setGuaranteeUserTrustAccountId(guar.getTrustAccountId());
            borrowInfo.setStatus(BorrowStatus.WAITING);
            borrowInfo.setInputStatus(InputStatus.WAIT);
            borrowInfo.setRaiseNum(0);
            borrowInfo.setRaiseMoney(0L);
            borrowInfo.setCreateTime(new Date());
            borrowInfo.setBorrowMoney(borrowInfo.getBorrowMoney() * 100);
            // borrowInfo.setMinInvest(Long.parseLong(ConfigUtil.getParameter("MIN_INVEST"))
            // * 100);
            // borrowInfo.setMaxInvest(Long.parseLong(ConfigUtil.getParameter("MAX_INVEST"))
            // * 100);
            // borrowInfo.setIncMoney(Long.parseLong(ConfigUtil.getParameter("INC_MONEY"))
            // * 100);

            serviceFactory.getPersistService().save(borrowInfo);
            return "/page/borrowInfo/addsuccess.jsp";
        } catch (Exception ex) {
            logger.error(ex);
            return "";
        }
    }

    /**
     * 导入身份证正面
     * 
     * @param request
     * @param map
     * @param filepath
     * @param printWriter
     */
    @RequestMapping(value = "/importidfront", method = RequestMethod.POST)
    public String importidfront(HttpServletRequest request, HttpServletResponse response, ModelMap map,
            @RequestParam MultipartFile idfront, String type) throws Exception {

        response.setContentType("text/html;charset=GBK");
        request.setCharacterEncoding("GBK");
        if (idfront.getSize() > 2 * 1024 * 1024) {
            map.put("info", "导入文件最大不能超过2M");
        } else {
            String filePath = request.getRealPath("/upload");// 取系统当前路径
            String newfileName = System.currentTimeMillis()
                    + idfront.getOriginalFilename().substring(idfront.getOriginalFilename().lastIndexOf('.'));
            OutputStream bos = new FileOutputStream(filePath + "/" + newfileName);
            InputStream in = idfront.getInputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);// 将文件写入服务器
            }
            bos.close();
            in.close();
            map.put("type", type);
            map.put("info", "success");
            map.put("filename", newfileName);
            map.put("filepath", SystemConfigUtil.getConfigValue("domainName") + "upload/" + newfileName);
        }
        return "/page/borrowInfo/importfile.jsp";
    }

    /**
     * 导入身份证反面
     * 
     * @param request
     * @param map
     * @param filepath
     * @param printWriter
     */
    @RequestMapping(value = "/importidback", method = RequestMethod.POST)
    public String importidback(HttpServletRequest request, HttpServletResponse response, ModelMap map,
            @RequestParam MultipartFile idback, String type) throws Exception {

        response.setContentType("text/html;charset=GBK");
        request.setCharacterEncoding("GBK");
        if (idback.getSize() > 2 * 1024 * 1024) {
            map.put("info", "导入文件最大不能超过2M");
        } else {
            String filePath = request.getRealPath("/upload");// 取系统当前路径
            String newfileName = System.currentTimeMillis()
                    + idback.getOriginalFilename().substring(idback.getOriginalFilename().lastIndexOf('.'));
            OutputStream bos = new FileOutputStream(filePath + "/" + newfileName);
            InputStream in = idback.getInputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);// 将文件写入服务器
            }
            bos.close();
            in.close();
            map.put("type", type);
            map.put("info", "success");
            map.put("filename", newfileName);
            map.put("filepath", SystemConfigUtil.getConfigValue("domainName") + "upload/" + newfileName);
        }
        return "/page/borrowInfo/importfile.jsp";
    }

    /**
     * 上传企业银行开户许可证
     * 
     * @param request
     * @param response
     * @param map
     * @param bankpermit
     * @param type
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/importbankpermit", method = RequestMethod.POST)
    public String importbankpermit(HttpServletRequest request, HttpServletResponse response, ModelMap map,
            @RequestParam MultipartFile bankpermit, String type) throws Exception {

        response.setContentType("text/html;charset=GBK");
        request.setCharacterEncoding("GBK");
        if (bankpermit.getSize() > 2 * 1024 * 1024) {
            map.put("info", "导入文件最大不能超过2M");
        } else {
            String filePath = request.getRealPath("/upload");// 取系统当前路径
            String newfileName = System.currentTimeMillis()
                    + bankpermit.getOriginalFilename().substring(bankpermit.getOriginalFilename().lastIndexOf('.'));
            OutputStream bos = new FileOutputStream(filePath + "/" + newfileName);
            InputStream in = bankpermit.getInputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);// 将文件写入服务器
            }
            bos.close();
            in.close();
            map.put("type", type);
            map.put("info", "success");
            map.put("filename", newfileName);
            map.put("filepath", SystemConfigUtil.getConfigValue("domainName") + "upload/" + newfileName);
        }
        return "/page/borrowInfo/importfile.jsp";
    }

    /**
     * 上传上年度利润报表
     * 
     * @param request
     * @param response
     * @param map
     * @param profit
     * @param type
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/importprofit", method = RequestMethod.POST)
    public String importprofit(HttpServletRequest request, HttpServletResponse response, ModelMap map,
            @RequestParam MultipartFile profit, String type) throws Exception {
        response.setContentType("text/html;charset=GBK");
        request.setCharacterEncoding("GBK");
        if (profit.getSize() > 2 * 1024 * 1024) {
            map.put("info", "导入文件最大不能超过2M");
        } else {
            String filePath = request.getRealPath("/upload");// 取系统当前路径
            String newfileName = System.currentTimeMillis()
                    + profit.getOriginalFilename().substring(profit.getOriginalFilename().lastIndexOf('.'));
            OutputStream bos = new FileOutputStream(filePath + "/" + newfileName);
            InputStream in = profit.getInputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);// 将文件写入服务器
            }
            bos.close();
            in.close();
            map.put("type", type);
            map.put("info", "success");
            map.put("filename", newfileName);
            map.put("filepath", SystemConfigUtil.getConfigValue("domainName") + "upload/" + newfileName);
        }
        return "/page/borrowInfo/importfile.jsp";
    }

    /**
     * <pre>
     * 转向申请借款额度
     * </pre>
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/toAddLimit")
    public String toAddLimit(ModelMap map, HttpServletRequest request) {
        return null;
    }
}
